package top.zackyoung.bbs.bean;

import com.alibaba.simpleimage.ImageWrapper;
import com.alibaba.simpleimage.SimpleImageException;
import com.alibaba.simpleimage.util.ImageReadHelper;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author: ZackYoung
 * @time: 2020/6/9
 */
public class CreateImage {
    private static final Logger logger = LogManager.getLogger(CreateImage.class);

    public void createImage(InputStream sourceInputStream, String outputPath, String extension, int x, int y, int width, int height, int scaleWidth, int scaleHeight) {
        try {
            if(extension != null && "gif".equalsIgnoreCase(extension)){
                Thumbnails.of(sourceInputStream)
                        .sourceRegion(x, y, width, height)//指定坐标(0, 0)和(400, 400)区域
                        .size(scaleWidth,scaleHeight)
                        .outputQuality(1)
                        .toFile(outputPath);
            }else{//阿里巴巴工具读取某些gif图片会出错
                ImageWrapper imageWrapper = ImageReadHelper.read(sourceInputStream);
                //outputQuality：输出的图片质量，范围：0.0~1.0，1为最高质量。注意使用该方法时输出的图片格式必须为jpg（即outputFormat("jpg")）。否则若是输出png格式图片，则该方法作用无效
                //watermark指定了水印，通过Positions指定水印位置，BufferedImage指定水印图片，第三个参数指定了水印的不透明性，范围为(0~1.0f),1.0f为不透明。
                //	.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("watermark.png")), 0.5f)
                Thumbnails.of(imageWrapper.getAsBufferedImage())
                        .sourceRegion(x, y, width, height)//指定坐标(0, 0)和(400, 400)区域
                        .size(scaleWidth,scaleHeight)
                        .outputQuality(1)
                        .toFile(outputPath);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            if (logger.isErrorEnabled()) {
                logger.error("生成缩略图IO错误",e);
            }
        } catch (SimpleImageException e) {
            // TODO Auto-generated catch block
            //	e.printStackTrace();
            if (logger.isErrorEnabled()) {
                logger.error("生成缩略图",e);
            }
        }finally {
            if(sourceInputStream != null){
                try {
                    sourceInputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    //		e.printStackTrace();
                    if (logger.isErrorEnabled()) {
                        logger.error("生成缩略图关闭输入流错误",e);
                    }
                }
            }

        }

    }
}
